package com.liu.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @DateTime 2015年3月26日 上午9:04:41
 * @Company 华视传媒
 * @Author 刘兴密
 * @QQ 63972012
 * @Desc web处理助手
 */
public class WebHelper {
	   private static String METHOD_SETHTTPONLY = "setHttpOnly";
	   private static boolean isSupportHttpOnly = false;

	    static { 
	        
	        Method[] methods = Cookie.class.getMethods();
	        for (int idx = 0; idx < methods.length; idx++) {
	            if (methods[idx].getName().equals(METHOD_SETHTTPONLY)) {
	                isSupportHttpOnly = true;
	            }
	        }
	    }
	
	 public static String getCookieString(String key, String val, String path,
			String domain) {
		String cookie = "";
		if (StrUtil.isNotNull(key) && StrUtil.isNotNull(val)) {
			cookie = key + "=" + val + "; ";
		}
		if (StrUtil.isNotNull(domain)) {
			cookie += "domain=" + domain + "; ";
		}
		if (StrUtil.isNotNull(path)) {
			cookie += "path=" + path + "; ";
		}
		return cookie;
	}

	 
	 
	  public static void setCookie(HttpServletResponse resp, String name, String value, String path, int exp) {
	        setCookie(resp, name, value, path, "", exp);
	    }

	    /**
	     * 得到cookie对象
	     * 
	     * @param resp HttpServletResponse
	     * @param name cookie名称
	     * @param value cookie的值
	     * @param path cookie的path值，默认为当前路径
	     * @param domain cookie的域名，默认为当前域
	     * @param exp 过期时间，设置为负数，表示session有效
	     */
	    public static Cookie getCookie(String name, String value, String path, String domain, int exp) {
	        Cookie cookie = new Cookie(name, value == null ? "" : value);
	        if (StrUtil.isNotNull(domain)) {
	            cookie.setDomain(domain);
	        }
	        if (exp >= 0) {
	            cookie.setMaxAge(exp);
	        }
	        if (StrUtil.isNotNull(path)) {
	            cookie.setPath(path);
	        }
	        return cookie;
	    }

	    public static void setCookie(HttpServletResponse resp, String name, String value, String domain) {
	        setCookie(resp, name, value, "/", domain, 0);
	    }

	    public static void setCookie(HttpServletResponse resp, String name, String value, String path, String domain, int exp) {
	        setCookie(resp, name, value, path, domain, exp, false, false);
	    }

	    public static void setCookie(HttpServletResponse resp, String name, String value, String path, String domain, int exp, boolean httpOnly) {
	        setCookie(resp, name, value, path, domain, exp, httpOnly, false);
	    }

	    /**
	     * 写cookie方法
	     * 
	     * @param resp HttpServletResponse
	     * @param name cookie名称
	     * @param value cookie的值
	     * @param path cookie的path值，默认为当前路径
	     * @param domain cookie的域名，默认为当前域
	     * @param exp 过期时间，设置为负数，表示session有效
	     */
	    public static void setCookie(HttpServletResponse resp, String name, String value, String path, String domain, int exp, boolean httpOnly, boolean isSecure) {
	        String val = (value == null) ? "" : value;
	        try {
	            val = URLEncoder.encode(val, "UTF-8");
	        } catch (UnsupportedEncodingException e) {
	            val = value;
	        }
	        Cookie cookie = new Cookie(name, val);
	        
	        if (StrUtil.isNotNull(domain)) {
	            cookie.setDomain(domain);
	        }
	        if (exp >= 0) {
	            cookie.setMaxAge(exp);
	        }
	        if (StrUtil.isNotNull(path)) {
	            cookie.setPath(path);
	        }

	        if (isSecure) {
	            cookie.setSecure(true);
	        }
	        
	        if(isSupportHttpOnly){
	        	cookie.setHttpOnly(true);
	        }
	        
	        resp.addCookie(cookie);
	    }
	 
	  
	
	/**
     * 清空指定cookie
     * 
     * @param req
     * @param resp
     * @param path 清空指定路cookie
     */
    public static void clearCookie(HttpServletRequest req,
            HttpServletResponse resp, String name,String path, String domain) {
        try {
            Cookie cookie = new Cookie(name, "");
            cookie.setMaxAge(0);
            cookie.setPath(path);// 根据你创建cookie的路径进行填写
            if (StrUtil.isNotNull(domain)) {
                cookie.setDomain(domain);
            }
            resp.addCookie(cookie);
        } catch (Exception ex) {
        }
    }

	
	  /**
	   *  @Date 2012-6-27 上午09:01:23
	   * @Author liuxingmi
	   * @Description 获取当前web域名url
	   * @param request
	   * @return String
	   */
	  public static String getContextUrl(HttpServletRequest request){
		  StringBuffer url = request.getRequestURL();
		  String contextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length())
			                         .append(request.getContextPath()).append("/").toString();

		  return contextUrl;
	  }
	  

		
		/**
		 * 获取cookie值
		 * 
		 * @param req
		 * @return
		 */
		public static String getCookieValue(HttpServletRequest req, String para) {
			Cookie[] cookies = req.getCookies();
			if (cookies != null) {
				for (Cookie c : cookies) {
					if (para.equals(c.getName())) {
						try {
							return URLDecoder.decode(c.getValue(),
									"utf-8");
						} catch (UnsupportedEncodingException e) {
							return c.getValue();
						}
					}
				}
			}
			return "";
		}
		/**
		 * @Date 2013-3-13 上午10:58:36
		 * @Author liuxingmi
		 * @Description 
		 * @param request
		 * @return String
		 */
		public static String getContentPath(HttpServletRequest request) {
			String path = request.getContextPath();
			return (StrUtil.isNull(path)) ? "/" : path;
		}
		
	    public static String getMainDomain(HttpServletRequest req) {

	        return  req.getServerName();
	    }
	    
	    

	    /**
	     * @DateTime 2015年4月25日 上午10:58:59
	     * @Author 刘兴密
	     * @QQ 63972012
	     * @Desc 获取 http body 数据
	     * @param request
	     * @return
	     * String
	     */
		public static String getHttpBody(HttpServletRequest request){
			String data = "";
			try {
				InputStream in = request.getInputStream();
				InputStreamReader isr = new InputStreamReader(in, "utf-8");
				BufferedReader br = new BufferedReader(isr);			
				String temp = "";
				while ((temp = br.readLine()) != null) {
					data += temp;
				}
				
			} catch (IOException e) {
			   e.printStackTrace();
			}
			if(data.indexOf("BODY_DATA") != -1){//兼容前端不能post json数据 的情况
				try {
					data = URLDecoder.decode(data.substring("BODY_DATA=".length()),"utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
		    }
			
			return data;
		}
		
		public static String getCookiesKey(String userId, String sid){
			
			int hc = MD5Util.MD5("good moring" + userId + sid).hashCode();
			String key = String.valueOf(hc).replace("-", "0");
			
			return key;
		}

}
